<template>
  <div class="select-study-module">
    <!-- 页面标题 -->
    <!-- <header class="header">
      <h1>单词易记智能英语</h1>
    </header> -->
    <!-- 顶部 semester -->
    <nav class="semester-list">
      <button
        v-for="semesterItem in semesterList"
        :key="semesterItem.id"
        :class="[
          'semester-item',
          { active: semesterItem.id === selectedSemesterId },
        ]"
        @click="handleSemesterChange(semesterItem.id)"
      >
        {{ semesterItem.nameZhCn }}
      </button>
    </nav>
    <div class="main-content">
      <!-- 左侧 series 列表 -->
      <aside class="serie-list">
        <div
          v-for="serieItem in serieList"
          :key="serieItem.id"
          :class="[
            'serie-item',
            { selected: serieItem.id === selectedSeriesId },
          ]"
          @click="handleSerieSelect(serieItem.id)"
        >
          <span class="icon-a">A</span>
          <span class="version-name">{{ serieItem.nameZhCn }}</span>
        </div>
      </aside>
      <!-- 右侧 programs 列表 -->
      <section class="program-cards">
        <div
          v-for="proItem in programList"
          :key="proItem.id"
          class="program-card"
          @click="handleModuleClick(proItem)"
        >
          <div class="program-title">{{ proItem.nameZhCn }}</div>
          <div class="progress-ring">
            <!-- 进度环，使用 SVG 实现 -->
            <!-- <svg width="60" height="60">
              <circle
                class="progress-bg"
                cx="30"
                cy="30"
                r="26"
                stroke="#e0e7ef"
                stroke-width="6"
                fill="none"
              />
              <circle
                class="progress-bar"
                :stroke="'#409eff'"
                cx="30"
                cy="30"
                r="26"
                stroke-width="6"
                fill="none"
                :stroke-dasharray="circumference"
                :stroke-dashoffset="
                  circumference - programItem.percent * circumference
                "
                stroke-linecap="round"
                transform="rotate(-90 30 30)"
              />
              <text
                x="30"
                y="36"
                text-anchor="middle"
                font-size="16"
                fill="#409eff"
              >
                {{ Math.round(programItem.percent * 100) }}%
              </text>
            </svg> -->
          </div>
          <div class="program-words">
            <!-- {{ proItem.studyNumber }}/{{ proItem.totalWords }} 单词 -->
            {{ proItem.totalWords }} 个单词
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'DcyxSelectStudyModule',
  inheritAttrs: false,
})

// import { ref, onMounted } from 'vue'
import {
  useDcyxSeriesStore,
  useDcyxUserStore,
  useDcyxProgramStore,
} from '@/store'
import type { Semester, Series } from '@/api/dcyx/series.api'
import type {
  ProgramItem,
  UpdateUserCurrentProgramPayload,
} from '@/api/dcyx/program.api'
// import { selectKey } from 'element-plus'

const dcyxUserStore = useDcyxUserStore()
const dcyxSeriesStore = useDcyxSeriesStore()
const dcyxProgramStore = useDcyxProgramStore()
const selectedSemesterId = ref<number | null>(null)
const selectedSeriesId = ref<number | null>(null)

const semesterList = ref<Semester[]>([])
const serieList = ref<Series[]>([])
const programList = ref<ProgramItem[]>([])

// const tabList = ref<TabItem[]>([])
// const serieList = ref<SerieItem[]>([])
// const programList = ref<ProgramItem[]>([])

// 进度环周长
// const circumference = 2 * Math.PI * 26

const emits = defineEmits(['closeDialog'])

// 模块 program 卡片点击，更新选中 program
/**
 * 处理逻辑：
 * 1、检查选中 unit 是否与当前 unit 相同
 * 2、如果相同，则不进行任何操作
 * 3、如果不同，则更新选中 unit
 * 4、跳转到具体单词学习页面或弹窗
 * @param programItem
 */
const handleModuleClick = async (programItem: ProgramItem) => {
  if (dcyxUserStore.userInfo && dcyxUserStore.userInfo.id) {
    try {
      await dcyxProgramStore.updateUserCurrentProgram({
        programId: Number(programItem.id),
        unitId: null,
      } as UpdateUserCurrentProgramPayload)
      await dcyxProgramStore.fetchCurrentProgram()
      emits('closeDialog')
    } catch (error) {
      console.error('handleModuleClick: 更新选中 program 失败', error)
    }
  }
}

// Handle tab changes
// 点击学期，如果选中学期变动
//  1、获取 series 列表、默认选中首个 series，获取 programs 列表
const handleSemesterChange = async (semesterId: number) => {
  selectedSemesterId.value = semesterId
  try {
    const newseriesList =
      await dcyxSeriesStore.fetchSeriesBySemesterId(semesterId)
    serieList.value = newseriesList
    selectedSeriesId.value = newseriesList[0].id
    const newprogramList = await dcyxProgramStore.getProgramBySeriesId(
      newseriesList[0].id,
    )
    programList.value = newprogramList
  } catch (error) {
    console.error('handleSemesterChange failed', error)
  }
}

// Handle version selection
// 点击 series，如果选中 series 变动
//  1、获取 programs 列表
const handleSerieSelect = async (seriesId: number) => {
  selectedSeriesId.value = seriesId
  try {
    const newprogramList = await dcyxProgramStore.getProgramBySeriesId(seriesId)
    programList.value = newprogramList
  } catch (error) {
    console.error('handleSerieSelect failed', error)
  }
}

// 获取 series 列表  series/getSeriesByUser  GET
// 设置 选中的 series
// 获取 seriesParent 列表  series/getSeriesByParentId/:id  GET
// 设置 选中的 seriesParent
// 获取 programs 列表  program/getProgramBySeriesId/:id  GET
// study/state/getCurrentProgram GET 查询得到 seriesId、parentSeriesId 为选中的 series 与 seriesParent;
const initSelectStudyModule = async () => {
  try {
    // 获取 semester 学期列表,并默认获取第一个 semester 下的 series 列表
    // await dcyxSeriesStore.initSeriesStore()
    // 获取 program 学习项目列表
    // await dcyxProgramStore.getProgramBySeriesId(selectedSeriesId.value)

    selectedSemesterId.value = dcyxSeriesStore.currentSemesterId || null
    selectedSeriesId.value = dcyxSeriesStore.currentSeriesId || null
    semesterList.value = dcyxSeriesStore.semesterList
    serieList.value = dcyxSeriesStore.serieList
    programList.value = dcyxProgramStore.programList
  } catch (error) {
    console.error('initSelectStudyModule failed', error)
  }
}

// 初始化加载
onMounted(() => {
  initSelectStudyModule()
})
</script>

<style scoped>
.select-study-module {
  display: flex;
  flex-direction: column;
  height: 600px;
  background: #f6f8fa;
}
.header {
  text-align: center;
  padding: 16px 0 8px 0;
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  background: #fff;
  box-shadow: 0 1px 4px #f0f1f2;
}
.semester-list {
  display: flex;
  justify-content: center;
  background: #fff;
  border-bottom: 1px solid #e0e7ef;
  padding: 4px 0;
}
.semester-item {
  margin: 0 12px;
  padding: 6px 16px;
  border-radius: 16px;
  background: none;
  border: none;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition:
    background 0.2s,
    color 0.2s;
}
.semester-item.active {
  background: #409eff;
  color: #fff;
}
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}
.serie-list {
  width: 160px;
  background: #fff;
  border-right: 1px solid #e0e7ef;
  overflow-y: auto;
  padding: 12px 0;
}
.serie-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 6px;
  margin-bottom: 4px;
  transition: background 0.2s;
}
.serie-item.selected {
  background: #e3f0fe;
  color: #409eff;
}
.icon-a {
  display: inline-block;
  width: 20px;
  height: 20px;
  background: #409eff;
  color: #fff;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  font-size: 14px;
  margin-right: 8px;
}
.version-name {
  font-size: 14px;
}
.program-cards {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px;
  overflow-y: auto;
  background: #f6f8fa;
}
.program-card {
  width: 100%;
  background: #e3f0fe;
  border-radius: 12px;
  box-shadow: 0 1px 4px #e0e7ef;
  padding: 16px 0 12px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition:
    box-shadow 0.2s,
    transform 0.2s;
}
.program-card:hover {
  box-shadow: 0 2px 8px #b3d8fd;
  transform: translateY(-1px) scale(1.02);
}
.program-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #409eff;
}
.progress-ring {
  margin-bottom: 8px;
}
.progress-ring svg {
  width: 50px;
  height: 50px;
}
.progress-ring circle {
  cx: 25;
  cy: 25;
  r: 22;
  stroke-width: 4;
}
.progress-ring text {
  x: 25;
  y: 30;
  font-size: 14px;
}
.program-words {
  font-size: 13px;
  color: #666;
  margin-top: 2px;
}
</style>
